#!/usr/bin/env node

/*
 * @Author: internoma
 * @Date:   2016-07-29 17:01:55
 * @Last Modified by:   internoma
 * @Last Modified time: 2016-07-30 19:19:58
 */

'use strict';

var MongoClient = require('mongodb').MongoClient;
var assert      = require('assert-plus');
var ObjectId    = require('mongodb').ObjectID;
var faker       = require('faker');
var faker       = require('faker/locale/es');
var readline    = require('readline');

var usersCursor    = [];
var articlesCursor = [];
var authorsCursor  = [];
var numUserRows    = 0;
var numArticleRows = 0;
var numAuthorRows  = 0;

var redColor    = '\x1b[31m';
var blueColor   = '\x1b[36m';
var greenColor  = '\x1b[32m';
var yellowColor = '\x1b[33m';
var purpleColor = '\x1b[34m';
var pinkColor   = '\x1b[35m';
var whiteColor  = '\x1b[37m';
var resetColor  = '\x1b[0m';

var inputCLI = function(question, callback) {
	var rl = readline.createInterface({
		input: process.stdin,
		output: process.stdout
	});
	rl.question(question, function(answer) {
		rl.close();
		callback(answer);
	});
};

var insertUsers = function(db, callback) {
	db.collection('users').drop();
	db.collection('users').insert(usersCursor, function(err, result) {
		assert.equal(err, null);
		console.log("\n***** Inserted " + numUserRows + " document/s into the users collection.");
		callback();
	});
};
var insertArticles = function(db, callback) {
	db.collection('articles').drop();
	db.collection('articles').ensureIndex({"post":"text"});
	db.collection('articles').insert(articlesCursor, function(err, result) {
		assert.equal(err, null);
		console.log("\n***** Inserted " + numArticleRows + " document/s into the articles collection.");
		callback();
	});
};
var insertAuthors = function(db, callback) {
	db.collection('authors').drop();
	db.collection('authors').insert(authorsCursor, function(err, result) {
		assert.equal(err, null);
		console.log("\n***** Inserted " + numAuthorRows + " document/s into the authors collection.");
		callback();
	});
};

var main = function(userRows, articleRows, authorRows, cb) {

	var url = 'mongodb://localhost:27017/miBBDD';

	var callback = cb;

	// set locale
	faker.locale = "es";

	numUserRows    = userRows;
	numArticleRows = articleRows;
	numAuthorRows  = authorRows;

	for (var i = numUserRows - 1; i >= 0; i--) {
		usersCursor.push({
			"uuid"      : faker.random.uuid(),
			"active"    : faker.random.boolean(),
			"name"      : {
				"firstname" : faker.name.firstName(),
				"lastname"  : faker.name.lastName() + ' ' + faker.name.lastName(),
			},
			"username"  : faker.internet.userName(),
			"password"  : faker.internet.password(),
			"email"     : faker.internet.email().toLowerCase(),
			"latitude"  : faker.address.latitude(),
			"longitude" : faker.address.longitude(),
			"createdAt" : new Date(),
			"deletedAt" : new Date("2000-01-01T00:00:00Z"),
		});
	}

	faker.locale = "es";

	for (var i = numArticleRows - 1; i >= 0; i--) {
		articlesCursor.push({
			"uuid"      : faker.random.uuid(),
			"active"    : faker.random.boolean(),
			"author"    : faker.random.uuid(),
			"title"     : faker.lorem.sentence(),
			"slug"      : faker.helpers.slugify(faker.lorem.sentence()).toLowerCase(),
			"post"      : faker.lorem.paragraphs(20,'\n\r'),
			"category"  : [
			faker.random.arrayElement(['javascript', 'nodejs', 'mvc', 'express', 'mongodb']),
			faker.random.arrayElement(['javascript', 'nodejs', 'mvc', 'express', 'mongodb'])
			],
			"createdAt" : new Date(),
			"deletedAt" : new Date("2000-01-01T00:00:00Z"),
		});
	}

	for (var i = numAuthorRows - 1; i >= 0; i--) {
		authorsCursor.push({
			"uuid"      : faker.random.uuid(),
			"firstname" : faker.name.firstName(),
			"lastname"  : faker.name.lastName() + ' ' + faker.name.lastName(),
			"email"     : faker.internet.email().toLowerCase(),
			"createdAt" : new Date(),
			"deletedAt" : new Date("2000-01-01T00:00:00Z"),
		});
	}

	MongoClient.connect(url, function(err, db) {
		assert.equal(null, err);
		var busy = 3;
		if (numUserRows > 0) {
			insertUsers(db, function(){
				console.log('The process has been completed...');
				busy--; if (!busy) callback();
			});
		} else {
			console.log('Not inserted documents in collection [users].');
		}
		if (numArticleRows > 0) {
			insertArticles(db, function(){
				console.log('The process has been completed...');
				busy--; if (!busy) callback();
			});
		} else {
			console.log('Not inserted documents in collection [articles].');
		}
		if (numAuthorRows > 0) {
			insertAuthors(db, function(){
				console.log('The process has been completed...');
				busy--; if (!busy) callback();
			});
		} else {
			console.log('Not inserted documents in collection [authors].');
			callback();
		}
	});

};

var schema = {
	properties: {
		numUserRows: {
			description: 'Number of documents for [users] collection: ',
			pattern: /^[0-9]+$/,
			message: 'the input must be only numbers.',
			default: 0,
			required: true
		},
		numArticleRows: {
			description: 'Number of documents for [articles] collection: ',
			pattern: /^[0-9]+$/,
			message: 'the input must be only numbers.',
			default: 0,
			required: true
		},
		numAuthorRows: {
			description: 'Number of documents for [authors] collection: ',
			pattern: /^[0-9]+$/,
			message: 'the input must be only numbers.',
			default: 0,
			required: true
		}
	}
};

// clear console
process.stdout.write('\x1B[2J\x1B[0f');

console.log(blueColor   + '******************************************');
console.log(greenColor  + 'Galgo JS populate database v.1.0.0 by @Alf');
console.log(blueColor   + '******************************************');
console.log(yellowColor + '\nIndicates the number of rows (0 for not generate):\n');

inputCLI(greenColor + 'Number of documents for '+redColor+'[users]'+whiteColor+' collection: ', function(answer) {
	numUserRows = answer;
	inputCLI(greenColor + 'Number of documents for '+redColor+'[articles]'+whiteColor+' collection: ', function(answer) {
		numArticleRows = answer;
		inputCLI(greenColor + 'Number of documents for '+redColor+'[authors]'+whiteColor+' collection: ', function(answer) {
			numAuthorRows = answer;
			main(numUserRows, numArticleRows, numAuthorRows, function(){
				console.log('\nYou have a good day...');
				process.exit(0);
			});
		});
	});
});